import os
from pathlib import Path
import fitz
from docx import Document
from docx.shared import Inches


def pdf_to_images(pdf_path, output_dir="temp_images"):
    """将PDF转换为图片"""
    try:
        # 打开PDF文件
        pdf_document = fitz.open(pdf_path)
        image_paths = []

        # 创建临时图片目录
        Path(output_dir).mkdir(exist_ok=True)

        # 逐页转换PDF为图片
        for page_num in range(len(pdf_document)):
            page = pdf_document[page_num]

            # 设置图片缩放比例（提高清晰度）
            mat = fitz.Matrix(2.0, 2.0)  # 200%缩放
            pix = page.get_pixmap(matrix=mat)

            # 保存图片
            image_path = os.path.join(output_dir, f"page_{page_num + 1}.png")
            pix.save(image_path)
            image_paths.append(image_path)

        pdf_document.close()
        return image_paths

    except Exception as e:
        print(f"PDF转图片失败: {e}")
        return []


def images_to_word(image_paths, output_path):
    """将图片插入到Word文档"""
    try:
        doc = Document()

        for i, image_path in enumerate(image_paths):
            # 在Word中插入图片
            doc.add_picture(image_path, width=Inches(6.0))  # 设置图片宽度为6英寸

            # 如果不是最后一页，添加分页符
            if i < len(image_paths) - 1:
                doc.add_page_break()

        # 保存Word文档
        doc.save(output_path)
        return True

    except Exception as e:
        print(f"图片转Word失败: {e}")
        return False


def clean_temp_files(image_paths):
    """清理临时图片文件"""
    for image_path in image_paths:
        try:
            os.remove(image_path)
        except:
            pass
    try:
        os.rmdir("temp_images")
    except:
        pass


def pdf_to_word(pdf_path, word_path=None):
    """主函数：将PDF转换为Word文档"""
    if not os.path.exists(pdf_path):
        print(f"错误：PDF文件不存在 - {pdf_path}")
        return False

    if word_path is None:
        # 自动生成输出路径
        base_name = os.path.splitext(pdf_path)[0]
        word_path = f"{base_name}.docx"

    print(f"开始转换: {pdf_path} -> {word_path}")

    # 步骤1: PDF转图片
    print("正在将PDF转换为图片...")
    image_paths = pdf_to_images(pdf_path)

    if not image_paths:
        print("转换失败：无法从PDF提取图片")
        return False

    print(f"成功生成 {len(image_paths)} 张图片")

    # 步骤2: 图片插入Word
    print("正在将图片插入Word文档...")
    success = images_to_word(image_paths, word_path)

    # 清理临时文件
    clean_temp_files(image_paths)

    if success:
        print(f"转换完成！Word文档已保存至: {word_path}")
        return True
    else:
        print("转换失败")
        return False


if __name__ == "__main__":

    pdf_to_word(r'D:\测试\（新生儿）脑电记录仪20250528.pdf')